<template>
  <div
    class="virtual-scroll-container"
    :style="{ height: containerHeight + 'px' }"
    @scroll="handleScroll"
  >
    <div class="virtual-scroll-content" :style="{ height: totalHeight + 'px' }">
      <div
        class="virtual-scroll-items"
        :style="{ transform: `translateY(${offsetY}px)` }"
      >
        <div
          v-for="value in displayItems"
          :key="value.id"
          :style="{ height: itemHeight + 'px' }"
          class="virtual-scroll-item"
        >
          {{ value.text }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";

const props = defineProps<{
  items: any[];
  itemHeight: number;
  containerHeight: number;
}>();

const totalHeight = computed(() => {
  return props.items.length * props.itemHeight;
});

const scrollTop = ref(0);

function handleScroll(event: Event) {
  const target = event.target as HTMLElement;
  scrollTop.value = target.scrollTop;
}

const displayStart = computed(() => {
  return Math.floor(scrollTop.value / props.itemHeight);
});
const displayEnd = computed(() => {
  return Math.min(
    displayStart.value +
      Math.ceil(props.containerHeight / props.itemHeight) +
      1,
    props.items.length
  );
});
const displayItems = computed(() => {
  console.log(
    "displayItems:",
    displayStart.value,
    displayEnd.value,
    "offsetY:",
    offsetY.value,
    "scrollTop:",
    scrollTop.value
  );
  return props.items.slice(displayStart.value, displayEnd.value);
});

// 计算偏移量
const offsetY = computed(() => displayStart.value * props.itemHeight);
</script>

<style scoped>
.virtual-scroll-container {
  width: 100%;
  overflow: auto;
}

.virtual-scroll-content {
  position: relative;
}

.virtual-scroll-items {
  /* 测试1: 有 absolute 定位（正确） */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;

  /* 添加背景色来观察元素实际占用空间 */
  background-color: rgba(255, 0, 0, 0.1);
  border: 1px solid red;
}

.virtual-scroll-item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #f0f0f0;
}
</style>
